/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentLocale;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentLocaleForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Sets locale default if it is not
 * </p>
 * <p><a href="SetContentLocaleDefaultAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.16 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action path="/core/contentLocale/setDefault"
 * name="contentLocaleForm"
 * scope="request"
 * validate="false"
 * roles="core-contentLocale-setDefault"
 * @struts.action-forward name="listContentLocales"
 * path="/core/contentLocale/list.do"
 * redirect="true"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentLocale/list.do"
 */
public final class SetContentLocaleDefaultAction extends BaseAction {

	private transient MenuManager menuManager = null;

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		ContentLocaleForm contentLocaleForm = (ContentLocaleForm) form;

		String contentLocaleIdentifier = null;
		if ( !GenericValidator.isBlankOrNull(contentLocaleForm.getIdentifier()) ) {
			contentLocaleIdentifier = contentLocaleForm.getIdentifier();
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content locale ID. Returning to list.");
			}
			return mapping.findForward("listContentLocales");
		}

		if ( menuManager == null ) {
			menuManager = (MenuManager) getBean(Constants.MENU_MANAGER_BEAN);
		}

		ContentLocale contentLocale = LocaleUtil.getInstance(servlet.getServletContext()).retrieveContentLocale(contentLocaleIdentifier);

		if ( contentLocale == null ) {
			// content locale not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("contentLocaleNotFound", new ActionMessage("core.contentLocale.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listContentLocales");
		}

		boolean alreadyDefault = contentLocale.getDefaultInstance() != null ? contentLocale.getDefaultInstance().booleanValue() : false;

		try {
			if ( !alreadyDefault ) {
				ContentLocale defaultLocale = LocaleUtil.getInstance(servlet.getServletContext()).getDefaultLocale();
				if ( defaultLocale != null ) {
					defaultLocale.setDefaultInstance(Boolean.FALSE);
					LocaleUtil.getInstance(servlet.getServletContext()).updateContentLocale(defaultLocale);

					// we must change locale identifier of all hard-coded menu items
					List hardcodedItems = menuManager.listMenuItems(null).asList();
					for ( Iterator i = hardcodedItems.iterator(); i.hasNext(); ) {
						MenuItem menuItem = (MenuItem) i.next();
						processFieldValues(menuItem, contentLocale.getIdentifier());
					}
				}

				contentLocale.setDefaultInstance(Boolean.TRUE);
				contentLocale.setActive(Boolean.TRUE);
				contentLocale.setEnabled(Boolean.TRUE);
				LocaleUtil.getInstance(servlet.getServletContext()).updateContentLocale(contentLocale);
			}
		} catch ( ObjectOptimisticLockingFailureException e ) {
			// content locale was updated or deleted by another transaction
			ActionMessages errors = new ActionMessages();
			errors.add("updateFailed", new ActionMessage("core.contentLocale.errors.updateFailed"));
			saveErrors(request, errors);
			return mapping.findForward("listContentLocales");
		}

		return mapping.findForward("listContentLocales");
	}

	/**
	 * Changes locale identifier of title and tooltip fields of menu item
	 *
	 * @param menuItem         Menu item to process field values of
	 * @param localeIdentifier Locale identifier to set
	 */
	protected void processFieldValues(MenuItem menuItem, String localeIdentifier) {

		if ( menuItem.getTitle() != null && !menuItem.getTitle().isEmpty() ) {
			String title = (String) menuItem.getTitle().values().iterator().next();
			menuItem.getTitle().clear();
			menuItem.getTitle().put(localeIdentifier, title);
		}

		if ( menuItem.getToolTip() != null && !menuItem.getToolTip().isEmpty() ) {
			String toolTip = (String) menuItem.getToolTip().values().iterator().next();
			menuItem.getToolTip().clear();
			menuItem.getToolTip().put(localeIdentifier, toolTip);
		}

		// recursive call of this method on child items
		List childItems = menuItem.getChildItems();
		for ( Iterator i = childItems.iterator(); i.hasNext(); ) {
			MenuItem childItem = (MenuItem) i.next();
			if ( !childItem.isDynamic() ) {
				processFieldValues(childItem, localeIdentifier);
			}
		}

	}
}